/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.flipkart.ohos.proteus.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.StackLayout;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import com.flipkart.ohos.proteus.DemoApplication;
import com.flipkart.ohos.proteus.HiExecutor;
import com.flipkart.ohos.proteus.LayoutManager;
import com.flipkart.ohos.proteus.ProteusContext;
import com.flipkart.ohos.proteus.ProteusLayoutInflater;
import com.flipkart.ohos.proteus.ProteusView;
import com.flipkart.ohos.proteus.ResourceTable;
import com.flipkart.ohos.proteus.StyleManager;
import com.flipkart.ohos.proteus.Styles;
import com.flipkart.ohos.proteus.api.ProteusManager;
import com.flipkart.ohos.proteus.exceptions.ProteusInflateException;
import com.flipkart.ohos.proteus.value.ElementValue;
import com.flipkart.ohos.proteus.value.Layout;
import com.flipkart.ohos.proteus.value.ObjectValue;
import com.flipkart.ohos.proteus.value.Value;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class MainAbilitySlice extends AbilitySlice implements ProteusManager.Listener {
    private static final int DIALOG_WIGHT = 900;
    private static final int DIALOG_RADIUS = 5;
    private ProteusLayoutInflater proteusLayoutInflater;
    private ObjectValue data;
    private Layout layout;
    private Styles styles;
    private Map<String, Layout> layouts;
    private ProteusManager proteusManager;

    private final StyleManager styleManager = new StyleManager() {
        @Override
        protected Styles getStyles() {
            return styles;
        }
    };

    private final LayoutManager layoutManager = new LayoutManager() {
        @Override
        protected Map<String, Layout> getLayouts() {
            return layouts;
        }
    };

    /**
     * Simple implementation of ImageLoader for loading images from url in background.
     */
    private final ProteusLayoutInflater.ImageLoader loader = new ProteusLayoutInflater.ImageLoader() {
        @Override
        public void getSrcBitmap(ProteusView proteusView, String url, String size,
                                 final ElementValue.AsyncCallback asyncCallback) {
            ResourceManager resourceManager = getContext().getResourceManager();
            Resource resource;
            try {
                if (resourceManager != null) {
                    resource = resourceManager.getRawFileEntry(url).openRawFile();
                    ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                    decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
                    decodingOptions.desiredSize = new Size(Integer.parseInt(size), Integer.parseInt(size));
                    ImageSource imageSource = ImageSource.create(resource, new ImageSource.SourceOptions());
                    PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
                    asyncCallback.setElement(new PixelMapElement(pixelMap));
                    pixelMap.release();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void getUrlBitmap(ProteusView proteusView, String stringUrl, ElementValue.AsyncCallback asyncCallback) {
            HiExecutor.runBg(() -> {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(stringUrl);
                    URLConnection urlConnection = url.openConnection();
                    if (urlConnection instanceof HttpURLConnection) {
                        connection = (HttpURLConnection) urlConnection;
                    }
                    if (connection != null) {
                        connection.connect();
                        InputStream inputStream = urlConnection.getInputStream();
                        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                        decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
                        ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());
                        PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
                        asyncCallback.setElement(new PixelMapElement(pixelMap));
                        pixelMap.release();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    };

    private final ProteusLayoutInflater.Callback callback = new ProteusLayoutInflater.Callback() {
        @Override
        public ProteusView onUnknownViewType(ProteusContext context, String type, Layout proteusLayout,
                                             ObjectValue objectValue, int index) {
            try {
                throw new ProteusInflateException("Unknown view type '" + type + "' cannot be inflated");
            } catch (ProteusInflateException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public void onEvent(String event, Value value, ProteusView view) {
            // 此处用来处理点击事件等
            // 获取控件类型
            Button button = (Button) view.getAsView();
            switch (event) {
                case "click":
                    button.setText("按钮被点击了!!!");
                    present(new TwoAbilitySlice(), new Intent());
                    break;
                case "doubleClick":
                    button.setText("按钮被双击了!!!");
                    break;
                case "longClick":
                    button.setText("按钮被长按了!!!");
                    break;
                default:
                    break;
            }
        }
    };

    private StackLayout container;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        Image refresh = (Image) findComponentById(ResourceTable.Id_refresh);
        Image dialogButton = (Image) findComponentById(ResourceTable.Id_dialog_button);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setShape(ShapeElement.OVAL);
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#FE1289")));
        dialogButton.setBackground(shapeElement);
        container = (StackLayout) findComponentById(ResourceTable.Id_create_layout);
        refresh.setClickedListener(component -> {
            reload();
        });
        dialogButton.setClickedListener(component -> alert());

        proteusManager = DemoApplication.getProteusManager();
        ProteusContext proteusContext = proteusManager.getProteus().createContextBuilder(MainAbilitySlice.this)
            .setLayoutManager(layoutManager)
            .setCallback(callback)
            .setImageLoader(loader)
            .setStyleManager(styleManager)
            .build();

        proteusLayoutInflater = proteusContext.getInflater();
    }

    @Override
    public void onActive() {
        super.onActive();
        proteusManager.addListener(this);
        proteusManager.load();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        proteusManager.removeListener(this);
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void alert() {
        if (layout != null) {
            ProteusView proteusView = proteusLayoutInflater.inflate("AlertDialogLayout", data);
            CommonDialog commonDialog = new CommonDialog(this);
            commonDialog.setContentCustomComponent(proteusView.getAsView());
            commonDialog.setSize(DIALOG_WIGHT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
            commonDialog.setCornerRadius(DIALOG_RADIUS);
            commonDialog.setButton(IDialog.BUTTON3, "OK", (iDialog, i) -> iDialog.destroy());
            commonDialog.show();
        } else {
            new ToastDialog(getContext()).setText("layout is null").setAlignment(LayoutAlignment.CENTER).show();
        }
    }

    void render() {
        // remove the current view
        container.removeAllComponents();
        // Inflate a new view using proteus
        ProteusView view = proteusLayoutInflater.inflate(layout, data);
        // Add the inflated view to the container
        container.addComponent(view.getAsView());
    }

    void reload() {
        proteusManager.update();
    }

    @Override
    public void onLoad() {
        data = proteusManager.getData();
        layout = proteusManager.getRootLayout();
        layouts = proteusManager.getLayouts();
        styles = proteusManager.getStyles();
        render();
    }

    @Override
    public void onError(String e) {
        new ToastDialog(this)
            .setText(e)
            .setAlignment(LayoutAlignment.CENTER)
            .show();
    }
}
